<template>
  <div class="customerInfomation">
    <div class="header" v-if="!isWidget">
      <div class="customerName">
        <div class="cus_title">
          <span class="cus_name">{{openParams.title}}</span><i class="el-icon-star-on" v-if="openParams.isatention"></i>
        </div>
        <!-- <div class="tag">
          <span class="small_tag">成交用户</span>
          <span class="small_tag">五星</span>
        </div> -->
      </div>
      <div class="activity">
        <div
         class="act-btns"
          v-for="(activity,index) in formdata.activities"
          :key="index"
          :title="activity.name"
          @click="onAction(activity)"
        >
          {{activity.name}}
        </div>
      </div>
    </div>
    <div class="info" v-if="!isWidget">
      <span class="info_detail">
        <template v-for="(ite) in openParams.field">
         {{ite.name}}：{{ite.value}}
        </template>
      </span>
      <!-- <span class="info_detail">最后跟进时间：一周内</span> -->
    </div>
    <div class="stepMain" v-if="openParams.isstage">
      <div class="step_stage">
        <div class="fold" @click="handelFold"><i class="el-icon-arrow-down" :style="{'transform':!isShowStep ? 'rotate(180deg)':'' }"></i></div>
        <div class="step-box">
          <!-- item.backcolor -->
          <div class="bgDiv" v-for="(item,index) in stage" :key="index" :title="item.name" @click="handelStage(item.index)" :class="[index + 1 === active ? 'active' : '','step_once']" :style="{'backgroundColor': item.backcolor,'width': `calc(1/${stage.length}*100% - 10px)`}">
            <span class="stepName" :style="{'color': item.fontcolor}"><span class="ordernum">{{item.ordernum}}</span>&nbsp;&nbsp;{{item.name}}</span>
            <!-- <span class="stepName">0%</span> -->
          </div>
        </div>
      </div>
      <template v-if="!isWidget">
        <div class="step_contain" v-show="isShowStep">
          <div class="firstStep">
            <div class="onceStep" v-if="currentStage.chaillist && currentStage.chaillist[0]"><el-checkbox>({{currentStage.chaillist[0].schedule}}) {{currentStage.chaillist[0].taskname}}</el-checkbox></div>
            <div class="onceStep" v-if="currentStage.chaillist && currentStage.chaillist[1]"><el-checkbox>({{currentStage.chaillist[1].schedule}}) {{currentStage.chaillist[1].taskname}}</el-checkbox></div>
          </div>
          <div v-show="isShowStepContain" class="firstStep">
            <template v-for="(item,index) in currentStage.chaillist">
              <div class="onceStep"  :key="index" v-if="index > 1"><el-checkbox>({{item.schedule}}) {{item.taskname}}</el-checkbox></div>
            </template>
          </div>
          <div @click="foldContain" class="foldContain">
            <template v-if="!isShowStepContain">展开任务栏</template>
            <template v-else>折叠任务栏</template>
            <i class="el-icon-d-arrow-right" :style="{'transform':isShowStepContain ? 'rotate(-90deg)':'rotate(90deg)' }"></i>
          </div>
        </div>
      </template>
    </div>
    <div class="tabContain" v-if="!isWidget">
      <el-tabs v-model="activeName" @tab-click="handleClick" class="tabs">
        <el-tab-pane 
          v-for="(tab,index) in tabs" :key="index"
          :label="tab.name"
          :name="tab.id + '_' + index"
        >
          <el-input
            type="textarea"
            :rows="2"
            placeholder="快速录入跟进记录"
            @focus="quickEntry"
            v-model="textarea">
          </el-input>
          <div class="basicAndDynamics">
            <div class="basicInfo" v-if="tab.type == 'form'" :style="{'width': isDynamicsFold ? '70%' : '100%'}">
              <div class="headerTitle">基础信息</div>
              <div v-for="(ite,i) in tab.fields" :key="i" :class="['left', (ite.name == '扩展信息' || ite.name == '系统信息' || ite.name == '销售信息') ? 'leftTitle':'']">
                <template v-if="ite.formField == 'CalctextField'">
                  <span class="right" v-html="ite.value"></span>
                </template>
                <template v-else-if="ite.formField == 'UserField'">
                  {{ite.discript}}：<span class="right"> {{showName(ite.value,ite.data)}}</span>
                </template>
                <template v-else-if="ite.formField == 'SelectField'">
                  {{ite.discript}}：<span class="right"> {{showOption(ite.value,ite.options)}}</span>
                </template>
                <template v-else-if="ite.formField == 'ImageUploadField'">
                  {{ite.discript}}：
                  <span class="right rightImg" v-if="ite.value">
                    <template v-for="(el,index) in JSON.parse(ite.value)">
                      <img :src="el.url" alt="" :key="index">
                    </template>
                  </span>
                </template>
                <template v-else-if="ite.formField == 'AttachmentUploadField'">
                  {{ite.discript}}：
                  <span class="right" v-if="ite.value">
                    <template v-for="(el,index) in JSON.parse(ite.value)">
                      <div :key="index" @click="handlePreview(el)" class="fileBox">{{el.name}}</div>
                    </template>
                  </span>
                </template>
                <template v-else>
                  {{ite.discript}}：<span class="right"> {{ite.value}}</span>
                </template>
              </div>
            </div>
            <div class="basicInfo" v-else :style="{'width': isDynamicsFold ? '70%' : '100%'}">
              <listView :viewId="tab.id" :docId='openParams.docId' :appId="openParams.appId" :parentId="openParams.docId"></listView>
              <!-- <iframe
                ref="mainFrame"
                style="border:none"
                width="100%"
                height="100%"
                scrolling="yes"
                frameborder="0"
                allowtransparency="true" 
                noresize="noresize"
                :src="'/static/portal/vue/index.html#/open?appId=' + openParams.appId + '&actionContent=' + tab.id + '&linkType=01'"
              ></iframe> -->
            </div>
            <div class="dynamics" v-show="isDynamicsFold">
              <div class="headerTitle">
                <div>客户动态</div>
                <div class="dynamicsFold" @click="dynamicsFold"><i class="el-icon-arrow-right"></i></div>
              </div>
              <div class="timeLine">
                <el-timeline :reverse="false">
                  <el-timeline-item
                    v-for="(activity, index) in dynamicMsg"
                    :key="index"
                    placement="top"
                    :timestamp="activity.created">
                    {{activity.matter}}
                  </el-timeline-item>
                </el-timeline>
              </div>
            </div>
            <template v-if="openParams.isdynamic">
              <div class="headerTitle dynamicsFold" v-show="!isDynamicsFold" @click="dynamicsFold"><i class="el-icon-arrow-left"></i></div>
            </template>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
</template>

<script>
import {
  getStage,
  getForm,
  getDynamic,
  getHasPdfFile,
  getenvironment,
  runScript,
} from "@/api.js"
import listView from "@/components/listView.vue"
export default {
  props: [],
  components: {
    listView
  },
  data() {
    return {
      openParams: {},
      stage: [], //阶段数据
      currentStage: {},
      tabs: [],
      activeName:'',
      dynamicMsg: [],//动态信息
      formdata: {}, //表单数据
      active:1,
      isShowStep:true,//折叠
      isShowStepContain:false,//折叠阶段内容
      isDynamicsFold: true, //客户动态是否收缩。默认true张开
      isWidget:false,
      textarea: ''
    }
  },
  computed: {
  },
  created() {
    debugger
    console.log('1233333')
    let queryData = this.$route.query
    this.openParams = {
      docId: queryData.docid ? queryData.docid : queryData.docId ? queryData.docId :'',
      type: queryData.type ? queryData.type : '',
      formId: queryData.formid ? queryData.formid : queryData.formId ? queryData.formId :'',
      isstage: queryData.isstage ? (queryData.isstage == 'true' ? true : false) :true,//是否展示阶段
      isdynamic: queryData.isdynamic ? (queryData.isdynamic == 'true' ? true : false) :true, //是否展示动态
      title: queryData.title, //最上面显示的那个名称
      isatention: queryData.isatention ? (queryData.isatention == 'true' ? true : false) :true, //星标
      // field1name: queryData.field1name, //负责人那个位置
      // field1value: queryData.field1value, //周志军那个位置
      appId: obpmConfig.appId,
    }
    let href = location.href
    href = decodeURIComponent(href)
    href = href.replace(/&quot;/g,'"')
    let urlArrayF = href.split("?");
    let urlArray = '';
    if(urlArrayF[1]) {
      urlArray = urlArrayF[1].split("&");
    }
    let obj = {};
    if(urlArray && urlArray.length > 0) {
      for(let i=0; i<urlArray.length; i++) {
        let val = urlArray[i].split("=");
        obj[val[0]] = val[1];
      }
    }
    if(obj.field) {
      this.openParams.field = JSON.parse(obj.field)
    }
    this.isWidget = queryData.isWidget == 'true' ? true : false
   
    console.log(this.openParams,'openParams')
    this.toGetStage()
    this.initForm({
      appId: obpmConfig.appId,
      formId: this.openParams.formId,
      docId: this.openParams.docId,
    });
    if(this.openParams.isdynamic) {
      this.toGetDynamic()
    }else {
      this.isDynamicsFold = false
    }
  },
  methods: {
    quickEntry() {
      let params = {
        appId:obpmConfig.appId,
        actionContent: '__cCiE6t5Z7btgCHw8b99',
        name: '',
        linkType:'00',
      }
      top.obpmOAction('open-eject',params)
    },
    handlePreview(file) {
      debugger
      let isImg = false;
      let isVideo = false;
      let isIfc = false;
      let isOffice = false
      if(file.name) {
        let name = file.name.split('.')[file.name.split('.').length - 1];
        name = name.toLowerCase();
        if(
          name == 'png' || 
          name == 'jpg' || 
          name  == 'jpeg' || 
          name == 'gif' ) {
          isImg = true;
        }else if(
          name == 'mp3' || 
          name == 'mp4' 
        ) {
          isVideo = true;
        }else if(
          name == 'ifc'
        ) {
          isIfc = true;
        }
      }
      if(isVideo) {
        let url = window.location.origin + obpmFilePath + file.path
        window.open(url)
        return
      }
      if(isImg) {
        let imgPreview = document.getElementById('imgPreview')
        imgPreview.src = file.url
        document.getElementsByClassName('picture-preview-wrap')[0].style.display = ''
        return
      }
      let realName = file.path.split("/")[file.path.split("/").length - 1];
      getHasPdfFile(file.path, realName, {
        onSucess: res => {
            if(res.data.data){
                this.toGetenvironment(file,false)
            }else{
              this.$message({
                  message: '预览文件正在转换中，请稍后',
                  type: 'warning'
              });
            }
        },
        onError: error => {
        }
      })
    },
    toGetenvironment(file,onlineEdit) {
      debugger
      getenvironment(
				{
					onSucess: res => {
						if(res.data.errcode === 0) {
							if(res.data.data === true) {
                let realName = file.path.split("/")[file.path.split("/").length - 1];
                let pdfPath = '/static'
                let curEditUserId = top.trunkVariable.user.id
                let userName = top.trunkVariable.user.name
                let selectEditPlug = 'tray'
                let showTrackRevisions = true
                let url = pdfPath + '/portal/vue/pdf/pdfviewer.html?action=' + 'false' + 
                    "&path=" + file.path + 
                    "&name=" + realName + 
                    "&showName=" + file.name + 
                    "&waterMark=" + null + 
                    "&openWaterMark=" + false +
                    "&curEditUserId=" + curEditUserId  +
                    "&userName=" + userName + 
                    "&showTrackRevisions=" + showTrackRevisions +
                    "&selectEditPlug=" + selectEditPlug;
                    let URL = encodeURI(url)
                    window.open(URL);
							}
						}
					}
				}
			)
    },
    onAction(act) {
      console.log('点击了')
      let obj = {}
      obj.act = act
      if(act.type == 43) {
        runScript(
          obpmConfig.appId,
          act.id, 
          this.openParams.docId,
          'dispatcherUrl',
          '',
          '',
          {
            onSucess: response => {
              if(response.data.errcode === 0) {
                let url = response.data.data
                let urlParams = ''
                if(url.indexOf("?") > -1) {
                  urlParams = url.split("?")[1]
                }
                let isOpenCurrentSoftwareData = url.search("open?") != -1
                let urlArrayF = url.split("?")
                let urlArray = ''
                if(urlArrayF[1]) {
                  urlArray = urlArrayF[1].split("&")
                }
                let type = '';
                let params = {
                  linkType: type,
                  appId: obpmConfig.appId,
                  actionContent: '',
                  name: act.name,
                  _select: '',
                  viewId: "",
                };
                let obj = {};
                if(urlArray && urlArray.length > 0) {
                  for(let i=0; i<urlArray.length; i++) {
                    let val = urlArray[i].split("=");
                    obj[val[0]] = val[1];
                  }
                }
                obj.id = obj.id || Date.now()
                if(isOpenCurrentSoftwareData) {
                  let formParams = '';
                  for(let key in obj) {
                    if(
                      key != 'name' &&
                      key != 'actionContent' &&
                      key != 'searchData' && 
                      key != 'showtype' && 
                      key != 'realformId' && 
                      key != 'templateForm' && 
                      key != 'urlParams' && 
                      key != 'exparams' &&
                      key != 'runAfterParams' &&
                      key != 'queryString' &&
                      key != 'isOpenDialog'
                      ) {
                      if(obj[key]) {
                        formParams += "&" + key + '=' + obj[key];
                      }
                    }
                  }
                  if(formParams) {
                    obj.formParams = formParams
                  }
                  obj.name = act.name
                  obj.isPopupLayerDisplay = true
                  console.log(obj,'obj')
                  if(obj.linkType == '00') { //表单
                     top.obpmOAction('open-eject',obj)
                  }
                }
              }
            }
          }
        )
      }else {
        let params = {
          appId:obpmConfig.appId,
          actionContent: this.openParams.formId,
          _select: this.openParams.docId,
          linkType:'00',
        }
        top.obpmOAction('formAct',params,obj)
      }
    },
    //显示用户名
    showName(value,data) {
      if(value) {
        for(let i = 0; i < data.length; i ++) {
          if(data[i].id == value) {
            return data[i].name
          }
        }

      }else {
        return ''
      }

    },
    showOption(value,options) {
      if(value) {
        for(let i = 0; i < options.length; i ++) {
          if(options[i].value == value) {
            return options[i].option
          }
        }

      }else {
        return ''
      }
    },
    //获取动态
    toGetDynamic() {
      debugger
      getDynamic(
        this.openParams.type,
        this.openParams.docId,
        {
          onSucess: response => {
            if(response.data) {
              this.dynamicMsg = response.data
            }
          }
        }
      ) 
    },
    //初始化表单
    initForm({ appId, formId, docId}) {
      let obj = {
        _: new Date().getTime(),
      };
      getForm(
        appId,
        formId,
        docId,
        obj,
        // {},
        {
          onSucess: response => {
            let fd = response.data.data
            this.formdata = fd
            console.log(fd,'fd')
            let fields = fd.fields[0]
            this.tabs = fields.tabs
            this.activeName = this.tabs[0].id + '_' + 0
          }
        }
      )
    },
    //获取阶段
    toGetStage() {
      getStage(
        this.openParams.type,
        this.openParams.docId,
        {
          onSucess: response => {
            if(response.data) {
              let data = response.data
              this.stage = data
              for(let i = 0; i < this.stage.length; i ++) {
                if(this.stage[i].isdefault) {
                  this.currentStage = this.stage[i]
                  break;
                }
              }
            }
            console.log(response,'response')
          }
        }
      ) 
    },
    handleClick() {

    },
    handelFold() {
      this.isShowStep = !this.isShowStep
    },
    foldContain() {
      this.isShowStepContain = !this.isShowStepContain
    },
    //动态收缩
    dynamicsFold() {
      this.isDynamicsFold = !this.isDynamicsFold
    },
  },
}
</script>

<style>
@import "../assets/style/customerInformation.scss";
</style>